package com.glkj.vipsystem.config;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.glkj.vipsystem.entity.ao.ShopAO;
import com.glkj.vipsystem.entity.gen.Depot;
import com.glkj.vipsystem.service.IDepotService;
import com.glkj.vipsystem.service.IShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 项目启动成功后做点事情
 */
@Component
@Slf4j
public class ApplicationRunRunnerConfig implements ApplicationRunner {

    @Resource
    private IShopService shopService;
    @Resource
    private IDepotService depotService;

    /**
     * 项目启动成功后，初始化库存数据
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<ShopAO> shops = shopService.selectList(null);
        if (CollectionUtils.isEmpty(shops)) {
            return;
        }
        log.info("\n开始初始化店铺库存==============>");
        shops.forEach(shop -> {
            Integer shopId = shop.getId();
            // 暂时默认一店一仓
            Depot depot = depotService.selectOne(
                    new EntityWrapper<Depot>()
                            .eq("shop_id", shopId)
                            .last("limit 1")
            );
            // 有仓库 说明库存已初始化完成 跳过该店铺
            if (depot != null) {
                return;
            }
            // 初始化仓库
            try {
                depotService.initStock(shopId);
            } catch (Exception e){
                // do something
            }
        });
        log.info("\n初始化店铺库存完成==============>");
    }
}
